package com.rover.service.system;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.service.spi.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Charsets;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.io.Files;
import com.grid.Page;
import com.rover.dao.BaseDao;
import com.rover.entity.system.Role;
import com.rover.entity.system.RoleResource;

@Service
@Transactional
public class RoleService {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private BaseDao<Role> roleDao;

	@Autowired
	private BaseDao<RoleResource> roleResourceDao;

	@Transactional
	public Page<Role> query(Page<Role> page, String strWhere,
			Map<String, Object> params) {

		String hql = "from Role " + strWhere;
		hql += " order by name";
		page.setResult(roleDao.find(hql, params, page.getPageNo(),
				page.getPageSize()));
		String totalHql = "select count(*) " + hql;
		page.setTotalCount(roleDao.count(totalHql, params));
		return page;
		// return
		// userDao.find("select new Tuser(t.id,t.name,t.createdatetime,t.modifydatetime) from Tuser t ");
	}

	/*
	 * 获取所有角色
	 * */
	@Transactional
	public List<Role> getList() {
		String hql = "from Role " ;
		return roleDao.find(hql);
	}
	
	@Transactional
	public void save(Role role) {
		// 修改的时候删除原有资源
		if (role.getId() != null) {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("role_ID", role.getId());
			roleResourceDao.executeHql(
					"delete RoleResource t where t.role_ID=:role_ID", params);
		}
		roleDao.saveOrUpdate(role);
		String[] strResources = role.getResources().split(";");
		for (int i = 0; i < strResources.length; i++) {
			// 第一个是root-0节点，不要填入数据库
			if (i > 0) {
				RoleResource rr = new RoleResource();
				rr.setRole_ID(role.getId());
				rr.setResource_ID(Long.valueOf(strResources[i]));
				roleResourceDao.save(rr);
			}
		}
	}

	/*
	 * 删除数据
	 * @id 要删除的id号
	 * */
	@Transactional
	public void delete(Long id) {
		roleDao.delete(Role.class, id);
	}

	/*
	 * 获取角色id对应的资源名称和id号 返回结果是一个list 0是名称，1是对应的id
	 * @role_ID 要获取资源的Id号
	 * */
	@SuppressWarnings("unchecked")
	@Transactional
	public List<Object> getRoleResourceName(Long role_ID) {
		Query q = roleResourceDao
				.getCurrentSession()
				.createQuery(
						"select new list(r.text ,r.id) from Resource r,  RoleResource rr where r.id=rr.resource_ID and rr.role_ID=:role_ID");
		q.setLong("role_ID", role_ID);
		return q.list();
	}

	/*
	 * 添加的时候判断名称是否重复
	 * 
	 * @name 要判断的name
	 */
	@Transactional(readOnly = true)
	public Boolean isAddNameRepeat(String name) {
		List<Role> li = roleDao.find("from Role where name=?", name);
		if (li.size() > 0) {
			return true;
		} else
			return false;
	}

	/*
	 * 编辑的时候判断名称是否重复
	 * 
	 * @name 要判断的name
	 */
	@Transactional(readOnly = true)
	public Boolean isEditNameRepeat(String name, Long id) {
		List<Role> li = roleDao.find("from Role where name=? and id<>?", name,
				id);
		if (li.size() > 0) {
			return true;
		} else
			return false;
	}
	
	 //初始
	@Transactional
    public void initData() throws ServiceException{
		
        logger.debug("开始装载角色初始数据");
        File resourcetxt = new File(this.getClass().getResource("/data/role.txt").getFile());
        String star[] = {};
        try {
            List<String> lines = Files.readLines(resourcetxt, Charsets.UTF_8);

            Role re;
            int line = 1;
            for (String thisLine : lines) {
                //第一行是标题
                if (line == 1) {
                    line++;
                    continue;
                }

                Iterable<String> s = Splitter.on(",").split(thisLine);
                star = Iterables.toArray(s, String.class);

                if (star[0].trim().equals(""))
                    continue;
                List<Role> roles = roleDao.find("from Role where name=?", star[0].trim());
                if (roles != null && roles.size() != 0) {
                    continue;
                }
                re = new Role();
                re.setName(star[0].trim());
                re.setDescription(star[1].trim());

                this.roleDao.save(re);
            }
        } catch (Exception e) {
            logger.error("str[]:" + StringUtils.join(star, ","));
            logger.error("装载角色数据出错:" + e);
            throw new ServiceException("导入角色时，服务器发生异常");
        } finally {
           
        }
    }

}
